#include <stdio.h>
#include <stdarg.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

#include "fastlog.h"

/* 互斥机制 */
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

irqstate_t enter_critical_section(void)
{
    return pthread_mutex_lock(&mutex);
}

void leave_critical_section(irqstate_t flags)
{
    pthread_mutex_unlock(&mutex);
}

/* 系统时钟 */
static unsigned long sys_tick = 1;
unsigned long get_sys_tick(void)
{
    return sys_tick++;
}

/* 日志线程 */
static void *thread_log(void *arg)
{
    unsigned int thread_id = (unsigned int)(unsigned long)arg;
    unsigned int i = 0;
    int prio;

    if (thread_id == 3)
        prio = LOG_WARNING;
    else
        prio = LOG_INFO;
    
    while (1)
    {
        fastlog(prio, "%s id:%-9d, i:%05ld, i:%06u, i:0x%08x, %s :0x%08x\n", 
                    "test string", thread_id, i, i, i, "i << 8", i << 8);        
        i++;
        usleep(1);
    }

    return NULL;
}

static void prio_printf(int prio, const char *fmt, ...)
{
    if (prio > LOG_INFO)
        return;

    va_list ap;
    va_start(ap, fmt);
    vprintf(fmt, ap);
    va_end(ap);
}

/* 日志输出线程，用于空闲的时候将 log_buff 内容格式化输出 */
static void *thread_log_dump(void *arg)
{    
    while (1)
    {
        usleep(1000);
        
        if (fastlog_dump(prio_printf))
            exit(-1);
    }

    return NULL;
}

int main(void)
{
    unsigned int i;
    pthread_t tid;

    /* 启动日志线程 */
    for (i = 0; i < 10; i++)
    {
        pthread_create(&tid, NULL, thread_log, (void *)(unsigned long)i);
        pthread_detach(tid);
    }
    
    /* 启动日志输出线程，用于空闲的时候将 log_buff 内容格式化输出 */
    pthread_create(&tid, NULL, thread_log_dump, NULL);
    pthread_detach(tid);

    pause();
    
    return 0;
}

